import initQQmap from "/utils/initQQmap.js";

const getLocation = (config) => {
  return new Promise(async (resolve, reject) => {
    const resData = {
      ...config,
    };

    if (!config.latitude || !config.longitude) {
      const res = await wx
        .getLocation({
          type: "gcj02",
        })
        .catch((error) => {
          // console.error('获取经纬度错误', error)
          // addressText.value = '获取失败，请重新获取'
          // uni.showToast({
          // 	title: '地址信息获取失败，请重新获取',
          // 	icon: 'none',
          // 	duration: 2000
          // });
          reject({
            type: 1,
            message: "获取经纬度错误",
            error,
          });
        });
      // const speed = res.speed
      // const accuracy = res.accuracy

      if (!res) return false;

      resData.latitude = res.latitude;
      resData.longitude = res.longitude;
    }

    if (config.reverseGeocoder) {
      initQQmap().reverseGeocoder({
        // 位置坐标，默认获取当前位置，非必须参数
        location: {
          latitude: resData.latitude,
          longitude: resData.longitude,
        },
        success: function (res) {
          console.log(res);
          const { result } = res;
          const { address_component } = result;

          resData.reverseGeocoderResult = result;

          resolve(resData);
        },
        fail: function (error) {
          console.error("sdk转换错误", error);
          // addressText.value = '获取失败，请重新获取'
          // uni.showToast({
          // 	title: '地址信息转换失败，请重新获取',
          // 	icon: 'none',
          // 	duration: 2000
          // });
          reject({
            type: 2,
            message: "sdk转换错误",
            error,
          });
        },
      });
    }
  });
};

const getUserLocation = (config) => {
  // 不能用await，否则openSetting失效
  return new Promise(async (resolve, reject) => {
    wx.getSetting({
      success: async (res) => {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (
          res.authSetting["scope.userLocation"] != undefined &&
          res.authSetting["scope.userLocation"] != true
        ) {
          //未授权
          wx.showModal({
            title: config.settingTitle,
            content: config.settingContent,
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: "拒绝授权",
                  icon: "none",
                  duration: 1000,
                });
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: async function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: "授权成功",
                        icon: "success",
                        duration: 1000,
                      });
                      //再次授权，调用wx.getLocation的API
                      resolve(await getLocation(config));
                    } else {
                      wx.showToast({
                        title: "授权失败",
                        icon: "none",
                        duration: 1000,
                      });
                    }
                  },
                });
              }
            },
          });
        } else if (res.authSetting["scope.userLocation"] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          resolve(await getLocation(config));
        } else {
          console.log("授权成功");
          //调用wx.getLocation的API
          resolve(await getLocation(config));
        }
      },
    });
  });
};

export default {
  namespaced: true,
  state: {
    latitude: "",
    longitude: "",
    reverseGeocoderResult: {},
  },
  actions: {
    async getPosition({ commit, state }, config) {
      const positionData = await getUserLocation({
        ...config,
        ...state,
      });
      commit("SET_POSITION", positionData);
      return positionData;
    },
  },
  mutations: {
    SET_POSITION(state, data) {
      console.log("SET_POSITION", data);
      state.latitude = data.latitude;
      state.longitude = data.longitude;
      state.reverseGeocoderResult = data.reverseGeocoderResult;
    },
  },
};
